<template>
  <div class="booking-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>预约课程</h1>
      <p>选择您喜欢的私教和时间，开始您的健身之旅</p>
    </div>

    <!-- 私教信息 -->
    <div class="trainer-info-card" v-if="selectedTrainer">
      <img :src="selectedTrainer.avatar" :alt="selectedTrainer.name" class="trainer-avatar">
      <div class="trainer-details">
        <h3>{{ selectedTrainer.name }}</h3>
        <div class="trainer-meta">
          <span class="rating">⭐ {{ selectedTrainer.rating }}</span>
          <span class="experience">{{ selectedTrainer.experience }}年经验</span>
          <span class="location">{{ selectedTrainer.location }}</span>
        </div>
        <div class="specialties">
          <span v-for="specialty in selectedTrainer.specialties" :key="specialty" class="specialty-tag">
            {{ specialty }}
          </span>
        </div>
      </div>
      <div class="trainer-price">
        <span class="price">¥{{ selectedTrainer.price }}/课时</span>
      </div>
    </div>

    <!-- 预约步骤 -->
    <div class="booking-steps">
      <div class="step-indicator">
        <div class="step" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
          <span class="step-number">1</span>
          <span class="step-label">选择套餐</span>
        </div>
        <div class="step" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
          <span class="step-number">2</span>
          <span class="step-label">选择时间</span>
        </div>
        <div class="step" :class="{ active: currentStep >= 3, completed: currentStep > 3 }">
          <span class="step-number">3</span>
          <span class="step-label">确认支付</span>
        </div>
      </div>

      <!-- 步骤1: 选择套餐 -->
      <div v-if="currentStep === 1" class="step-content">
        <h3>选择课程套餐</h3>
        <div class="package-options">
          <div v-for="pkg in packages" :key="pkg.id" 
               class="package-card" 
               :class="{ selected: selectedPackage?.id === pkg.id }"
               @click="selectPackage(pkg)">
            <div class="package-header">
              <h4>{{ pkg.name }}</h4>
              <div class="package-badge" v-if="pkg.popular">热门</div>
            </div>
            <div class="package-details">
              <div class="package-price">
                <span class="price">¥{{ pkg.price }}</span>
                <span class="unit">{{ pkg.unit }}</span>
              </div>
              <div class="package-savings" v-if="pkg.savings">
                <span>节省 ¥{{ pkg.savings }}</span>
              </div>
              <ul class="package-features">
                <li v-for="feature in pkg.features" :key="feature">{{ feature }}</li>
              </ul>
            </div>
          </div>
        </div>
        <button @click="nextStep" :disabled="!selectedPackage" class="next-button">
          下一步
        </button>
      </div>

      <!-- 步骤2: 选择时间 -->
      <div v-if="currentStep === 2" class="step-content">
        <h3>选择上课时间</h3>
        <div class="calendar-container">
          <div class="calendar-header">
            <button @click="previousWeek" class="nav-button">‹</button>
            <span class="week-range">{{ weekRange }}</span>
            <button @click="nextWeek" class="nav-button">›</button>
          </div>
          
          <div class="calendar-grid">
            <div class="time-column">
              <div class="time-header">时间</div>
              <div v-for="time in timeSlots" :key="time" class="time-slot">
                {{ time }}
              </div>
            </div>
            
            <div v-for="day in weekDays" :key="day.date" class="day-column">
              <div class="day-header">
                <div class="day-name">{{ day.name }}</div>
                <div class="day-date">{{ day.date }}</div>
              </div>
              <div v-for="time in timeSlots" :key="time" 
                   class="time-cell"
                   :class="{ 
                     available: isTimeAvailable(day.date, time),
                     selected: isTimeSelected(day.date, time),
                     booked: isTimeBooked(day.date, time)
                   }"
                   @click="selectTime(day.date, time)">
                <span v-if="isTimeAvailable(day.date, time)">可预约</span>
                <span v-else-if="isTimeBooked(day.date, time)">已预约</span>
                <span v-else>不可用</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="selected-times" v-if="selectedTimes.length > 0">
          <h4>已选择的时间：</h4>
          <div class="time-tags">
            <span v-for="time in selectedTimes" :key="`${time.date}-${time.time}`" class="time-tag">
              {{ time.date }} {{ time.time }}
              <button @click="removeTime(time)" class="remove-time">×</button>
            </span>
          </div>
        </div>
        
        <div class="step-actions">
          <button @click="previousStep" class="prev-button">上一步</button>
          <button @click="nextStep" :disabled="selectedTimes.length === 0" class="next-button">
            下一步
          </button>
        </div>
      </div>

      <!-- 步骤3: 确认支付 -->
      <div v-if="currentStep === 3" class="step-content">
        <h3>确认订单</h3>
        
        <div class="order-summary">
          <div class="summary-section">
            <h4>课程信息</h4>
            <div class="summary-item">
              <span>私教：</span>
              <span>{{ selectedTrainer.name }}</span>
            </div>
            <div class="summary-item">
              <span>套餐：</span>
              <span>{{ selectedPackage.name }}</span>
            </div>
            <div class="summary-item">
              <span>课时数：</span>
              <span>{{ selectedTimes.length }} 课时</span>
            </div>
          </div>

          <div class="summary-section">
            <h4>上课时间</h4>
            <div class="time-list">
              <div v-for="time in selectedTimes" :key="`${time.date}-${time.time}`" class="time-item">
                {{ time.date }} {{ time.time }}
              </div>
            </div>
          </div>

          <div class="summary-section">
            <h4>费用明细</h4>
            <div class="cost-breakdown">
              <div class="cost-item">
                <span>课时费用：</span>
                <span>¥{{ courseCost }}</span>
              </div>
              <div class="cost-item" v-if="discount > 0">
                <span>套餐优惠：</span>
                <span class="discount">-¥{{ discount }}</span>
              </div>
              <div class="cost-item total">
                <span>总计：</span>
                <span>¥{{ totalCost }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="payment-methods">
          <h4>支付方式</h4>
          <div class="payment-options">
            <label v-for="method in paymentMethods" :key="method.id" class="payment-option">
              <input type="radio" v-model="selectedPaymentMethod" :value="method.id">
              <div class="payment-card">
                <i :class="method.icon"></i>
                <span>{{ method.name }}</span>
              </div>
            </label>
          </div>
        </div>

        <div class="booking-notes">
          <h4>预约须知</h4>
          <ul class="notes-list">
            <li>请提前15分钟到达训练场地</li>
            <li>如需取消课程，请提前24小时通知</li>
            <li>首次训练建议穿着运动服装</li>
            <li>平台提供7天无理由退款保障</li>
          </ul>
        </div>

        <div class="step-actions">
          <button @click="previousStep" class="prev-button">上一步</button>
          <button @click="confirmBooking" :disabled="!selectedPaymentMethod" class="confirm-button">
            确认预约并支付
          </button>
        </div>
      </div>
    </div>

    <!-- 预约成功弹窗 -->
    <div v-if="showSuccessModal" class="modal-overlay" @click="closeSuccessModal">
      <div class="success-modal" @click.stop>
        <div class="success-icon">✓</div>
        <h3>预约成功！</h3>
        <p>您的课程已成功预约，私教将在24小时内与您联系确认详细信息。</p>
        <div class="modal-actions">
          <button @click="goToProfile" class="profile-button">查看我的课程</button>
          <button @click="closeSuccessModal" class="close-button">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BookingView',
  data() {
    return {
      currentStep: 1,
      selectedTrainer: null,
      selectedPackage: null,
      selectedTimes: [],
      selectedPaymentMethod: '',
      showSuccessModal: false,
      currentWeekStart: new Date(),
      
      packages: [
        {
          id: 1,
          name: '单次体验',
          price: 280,
          unit: '/课时',
          savings: 0,
          popular: false,
          features: [
            '1对1专业指导',
            '个性化训练计划',
            '课后总结报告'
          ]
        },
        {
          id: 2,
          name: '月度套餐',
          price: 2200,
          unit: '/8课时',
          savings: 240,
          popular: true,
          features: [
            '8课时训练',
            '营养指导建议',
            '训练进度跟踪',
            '优先预约时段'
          ]
        },
        {
          id: 3,
          name: '季度套餐',
          price: 6300,
          unit: '/24课时',
          savings: 1020,
          popular: false,
          features: [
            '24课时训练',
            '全程营养指导',
            '体测数据分析',
            '专属训练计划',
            '7天无理由退款'
          ]
        }
      ],
      
      timeSlots: [
        '09:00', '10:00', '11:00', '14:00', 
        '15:00', '16:00', '17:00', '18:00', 
        '19:00', '20:00'
      ],
      
      paymentMethods: [
        { id: 'wechat', name: '微信支付', icon: 'payment-icon wechat' },
        { id: 'alipay', name: '支付宝', icon: 'payment-icon alipay' },
        { id: 'card', name: '银行卡', icon: 'payment-icon card' }
      ],
      
      // 模拟已预约的时间
      bookedTimes: [
        { date: '2024-01-15', time: '10:00' },
        { date: '2024-01-16', time: '14:00' },
        { date: '2024-01-17', time: '19:00' }
      ]
    }
  },
  
  computed: {
    weekDays() {
      const days = [];
      const start = new Date(this.currentWeekStart);
      
      for (let i = 0; i < 7; i++) {
        const date = new Date(start);
        date.setDate(start.getDate() + i);
        
        days.push({
          name: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()],
          date: date.toISOString().split('T')[0]
        });
      }
      
      return days;
    },
    
    weekRange() {
      const start = new Date(this.currentWeekStart);
      const end = new Date(start);
      end.setDate(start.getDate() + 6);
      
      return `${start.getMonth() + 1}月${start.getDate()}日 - ${end.getMonth() + 1}月${end.getDate()}日`;
    },
    
    courseCost() {
      if (!this.selectedPackage) return 0;
      
      if (this.selectedPackage.id === 1) {
        return this.selectedTimes.length * this.selectedPackage.price;
      }
      
      return this.selectedPackage.price;
    },
    
    discount() {
      return this.selectedPackage?.savings || 0;
    },
    
    totalCost() {
      return this.courseCost - this.discount;
    }
  },
  
  mounted() {
    this.loadTrainerInfo();
    this.setCurrentWeek();
  },
  
  methods: {
    loadTrainerInfo() {
      // 从路由参数或查询参数获取私教信息
      const trainerId = this.$route.query.trainer || 1;
      
      // 模拟数据 - 实际应用中会从API获取
      this.selectedTrainer = {
        id: trainerId,
        name: '张健',
        avatar: 'https://via.placeholder.com/80x80',
        rating: 4.9,
        experience: 5,
        location: '北京朝阳区',
        specialties: ['减脂塑形', '功能性训练'],
        price: 280
      };
    },
    
    setCurrentWeek() {
      const today = new Date();
      const dayOfWeek = today.getDay();
      const start = new Date(today);
      start.setDate(today.getDate() - dayOfWeek);
      this.currentWeekStart = start;
    },
    
    selectPackage(pkg) {
      this.selectedPackage = pkg;
    },
    
    nextStep() {
      if (this.currentStep < 3) {
        this.currentStep++;
      }
    },
    
    previousStep() {
      if (this.currentStep > 1) {
        this.currentStep--;
      }
    },
    
    previousWeek() {
      const newStart = new Date(this.currentWeekStart);
      newStart.setDate(newStart.getDate() - 7);
      this.currentWeekStart = newStart;
    },
    
    nextWeek() {
      const newStart = new Date(this.currentWeekStart);
      newStart.setDate(newStart.getDate() + 7);
      this.currentWeekStart = newStart;
    },
    
    isTimeAvailable(date, time) {
      // 检查时间是否可用（不在已预约列表中，且不是过去的时间）
      const now = new Date();
      const timeDate = new Date(`${date}T${time}:00`);
      
      if (timeDate < now) return false;
      
      return !this.bookedTimes.some(booked => 
        booked.date === date && booked.time === time
      );
    },
    
    isTimeSelected(date, time) {
      return this.selectedTimes.some(selected => 
        selected.date === date && selected.time === time
      );
    },
    
    isTimeBooked(date, time) {
      return this.bookedTimes.some(booked => 
        booked.date === date && booked.time === time
      );
    },
    
    selectTime(date, time) {
      if (!this.isTimeAvailable(date, time)) return;
      
      const timeSlot = { date, time };
      const index = this.selectedTimes.findIndex(t => 
        t.date === date && t.time === time
      );
      
      if (index > -1) {
        this.selectedTimes.splice(index, 1);
      } else {
        // 根据套餐限制选择的课时数
        const maxSessions = this.getMaxSessions();
        if (this.selectedTimes.length < maxSessions) {
          this.selectedTimes.push(timeSlot);
        }
      }
    },
    
    getMaxSessions() {
      if (!this.selectedPackage) return 1;
      
      switch (this.selectedPackage.id) {
        case 1: return 1;
        case 2: return 8;
        case 3: return 24;
        default: return 1;
      }
    },
    
    removeTime(timeToRemove) {
      const index = this.selectedTimes.findIndex(t => 
        t.date === timeToRemove.date && t.time === timeToRemove.time
      );
      if (index > -1) {
        this.selectedTimes.splice(index, 1);
      }
    },
    
    confirmBooking() {
      // 模拟支付处理
      setTimeout(() => {
        this.showSuccessModal = true;
      }, 1000);
    },
    
    closeSuccessModal() {
      this.showSuccessModal = false;
      this.$router.push('/');
    },
    
    goToProfile() {
      this.showSuccessModal = false;
      this.$router.push('/profile');
    }
  }
}
</script>

<style scoped>
.booking-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.trainer-info-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 20px;
}

.trainer-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.trainer-details {
  flex: 1;
}

.trainer-details h3 {
  color: #2c3e50;
  margin-bottom: 8px;
}

.trainer-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #7f8c8d;
}

.specialties {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.specialty-tag {
  background: #e3f2fd;
  color: #1976d2;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.trainer-price .price {
  font-size: 24px;
  font-weight: bold;
  color: #e74c3c;
}

.booking-steps {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.step-indicator {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  position: relative;
}

.step-indicator::before {
  content: '';
  position: absolute;
  top: 20px;
  left: 25%;
  right: 25%;
  height: 2px;
  background: #e9ecef;
  z-index: 1;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e9ecef;
  color: #6c757d;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.step.active .step-number {
  background: #3498db;
  color: white;
}

.step.completed .step-number {
  background: #27ae60;
  color: white;
}

.step-label {
  font-size: 14px;
  color: #6c757d;
}

.step.active .step-label {
  color: #2c3e50;
  font-weight: bold;
}

.step-content h3 {
  color: #2c3e50;
  margin-bottom: 20px;
  text-align: center;
}

.package-options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.package-card {
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.package-card:hover {
  border-color: #3498db;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
}

.package-card.selected {
  border-color: #3498db;
  background: #f8f9fa;
}

.package-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.package-badge {
  background: #e74c3c;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.package-price {
  margin-bottom: 10px;
}

.package-price .price {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

.package-price .unit {
  color: #7f8c8d;
  font-size: 14px;
}

.package-savings {
  color: #27ae60;
  font-size: 14px;
  margin-bottom: 15px;
}

.package-features {
  list-style: none;
  padding: 0;
  margin: 0;
}

.package-features li {
  padding: 4px 0;
  color: #555;
  position: relative;
  padding-left: 20px;
}

.package-features li::before {
  content: '✓';
  position: absolute;
  left: 0;
  color: #27ae60;
  font-weight: bold;
}

.calendar-container {
  margin-bottom: 30px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.nav-button {
  background: #3498db;
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  cursor: pointer;
  font-size: 18px;
}

.week-range {
  font-size: 18px;
  font-weight: bold;
  color: #2c3e50;
}

.calendar-grid {
  display: grid;
  grid-template-columns: 100px repeat(7, 1fr);
  gap: 1px;
  background: #e9ecef;
  border-radius: 8px;
  overflow: hidden;
}

.time-column, .day-column {
  background: white;
}

.time-header, .day-header {
  background: #f8f9fa;
  padding: 15px 10px;
  text-align: center;
  font-weight: bold;
  color: #2c3e50;
}

.day-header {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.day-name {
  font-size: 14px;
}

.day-date {
  font-size: 12px;
  color: #7f8c8d;
}

.time-slot {
  padding: 15px 10px;
  text-align: center;
  color: #7f8c8d;
  font-size: 14px;
}

.time-cell {
  padding: 15px 10px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 12px;
}

.time-cell.available {
  background: #e8f5e8;
  color: #27ae60;
}

.time-cell.available:hover {
  background: #d4edda;
}

.time-cell.selected {
  background: #3498db;
  color: white;
}

.time-cell.booked {
  background: #f8d7da;
  color: #721c24;
  cursor: not-allowed;
}

.selected-times {
  margin-bottom: 20px;
}

.time-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.time-tag {
  background: #3498db;
  color: white;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.remove-time {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 16px;
  padding: 0;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
}

.order-summary {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
}

.summary-section {
  margin-bottom: 20px;
}

.summary-section h4 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.time-list {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.time-item {
  background: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
}

.cost-breakdown {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.cost-item {
  display: flex;
  justify-content: space-between;
}

.cost-item.total {
  border-top: 1px solid #dee2e6;
  padding-top: 8px;
  font-weight: bold;
  font-size: 18px;
}

.discount {
  color: #27ae60;
}

.payment-methods {
  margin-bottom: 30px;
}

.payment-options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.payment-option input {
  display: none;
}

.payment-card {
  border: 2px solid #e9ecef;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.payment-card:hover {
  border-color: #3498db;
}

.payment-option input:checked + .payment-card {
  border-color: #3498db;
  background: #f8f9fa;
}

.booking-notes {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
}

.notes-list {
  margin: 10px 0 0 20px;
  color: #856404;
}

.step-actions {
  display: flex;
  justify-content: space-between;
  gap: 15px;
}

.next-button, .prev-button, .confirm-button {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.next-button, .confirm-button {
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
}

.next-button:hover:not(:disabled), .confirm-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}

.next-button:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.prev-button {
  background: #95a5a6;
  color: white;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.success-modal {
  background: white;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  max-width: 400px;
  width: 90%;
}

.success-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: #27ae60;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  margin: 0 auto 20px;
}

.modal-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 30px;
}

.profile-button, .close-button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
}

.profile-button {
  background: #3498db;
  color: white;
}

.close-button {
  background: #95a5a6;
  color: white;
}

@media (max-width: 768px) {
  .booking-container {
    padding: 15px;
  }
  
  .trainer-info-card {
    flex-direction: column;
    text-align: center;
  }
  
  .package-options {
    grid-template-columns: 1fr;
  }
  
  .calendar-grid {
    grid-template-columns: 80px repeat(7, 1fr);
    font-size: 12px;
  }
  
  .time-slot, .time-cell {
    padding: 10px 5px;
  }
  
  .payment-options {
    grid-template-columns: 1fr;
  }
  
  .step-actions {
    flex-direction: column;
  }
}
</style>